#include "common.h"
#include "devil1pld.h"
#define TYPE_ID_LENGTH 4

bool extractpld(const char *filedata,
               unsigned int filesize,
               const char *filename) {
    if (filedata == NULL || filesize <= 0 || filename == NULL) {
        return false;
    } 
    struct PldHeader h;
    DEVIL1PLD.getheader(&h, filedata);
    char *fn       = NULL;
    fn = (char*)malloc(strlen(filename) + 3 + 4);
    int size       = 0;
    unsigned int i = 0;
    char textureid[TYPE_ID_LENGTH] = {'\0', '2', '3', 'T'};
    for (i = 0; i < h.numOffset; i++) {
        const char * currentfile = filedata + h.offsets[i];
        size = DEVIL1PLD.sizeofsector(&h, i, filesize);
        if (strncmp( currentfile, textureid, TYPE_ID_LENGTH ) == 0)
          sprintf(fn, "%s_%d.txp", filename, i);
        else
          sprintf(fn, "%s_%d", filename, i);
        write(fn, currentfile, size);
    }
    free(fn);
    return true;
}

int main(int argc, char ** argv) {
    char *f = argv[1];
    unsigned int bufsize = 0;
    char *buffer         = loadfile(f, &bufsize);
    extractpld(buffer, bufsize, f);
    free(buffer);
    return 0;
}
